import moment from 'moment'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import axios from 'axios'
import { message } from 'antd'
import { transform } from 'lodash'

interface IDeepLoopFormateTreeOption {
  datas: any
  translate?: { value?: string; title?: string; key?: string; children?: string; extra?: string }
  originKey?: { value?: string; title?: string; children?: string }
}
export const deepLoopFormateTree = ({
  datas,
  translate = { value: 'value', title: 'title', key: 'key', children: 'children', extra: '' },
  originKey = { value: 'customId', title: 'text', children: 'child' },
}: IDeepLoopFormateTreeOption) => {
  if (!Array.isArray(datas) || datas.length == 0) {
    return datas
  }
  let res = []
  datas.map(data => {
    const { [originKey.children]: children, [originKey.value]: value, [originKey.title]: title } = data
    if (!value) {
      return
    }
    let item: any = {
      [translate.value]: value,
      [translate.title]: title,
      [translate.key]: value,
      [translate.children]: [],
    }
    if (children) {
      item[translate.children] = deepLoopFormateTree({ datas: children, translate, originKey })
    }
    if (translate.extra && data[translate.extra]) {
      item[translate.extra] = data[translate.extra]
    }
    res.push(item)
  })
  return res
}

export const findTreeNodeInfo = (datas, val, findKey = 'value', children = 'children') => {
  let info: any = {}
  const loop = datas => {
    if (!Array.isArray(datas) || datas.length == 0) {
      return
    }
    for (const key in datas) {
      if (datas.hasOwnProperty(key)) {
        if (val == datas[key][findKey]) {
          info = datas[key]
          return
        }
        datas[key][children] && loop(datas[key][children])
      }
    }
  }
  loop(datas)
  return info
}

export const findTreeParentInfo = (datas, val, findKey = 'value', children = 'children') => {
  let info: any = {}
  if (!val) {
    return
  }
  const loop = datas => {
    if (!Array.isArray(datas) || datas.length == 0) {
      return
    }
    for (const key in datas) {
      if (datas.hasOwnProperty(key)) {
        if (datas[key][children].some(item => item[findKey] === val)) {
          info = datas[key]
          return
        }
        datas[key][children] && loop(datas[key][children])
      }
    }
  }
  loop(datas)
  return info
}

export const debounce = (fn, wait = 500, delay = 300) => {
  let timer
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    let arg = arguments
    timer = setTimeout(() => {
      fn.apply(this, arg)
      timer = null
    }, wait)
  }
}

export const downBlobFile = (res, name, timeSuffix = true) => {
  const blob = new Blob([res], {
    type: 'application/vnd.ms-excel',
  })
  if (timeSuffix) {
    // 默认导出的文件名称添加时间
    const time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    name = name + ' ' + time
  }
  const fileName = `${name}.xls`
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveOrOpenBlob(blob, fileName)
  } else {
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink) 
  }
}

export const downBlobFileXlsx = (res, name, timeSuffix = true) => {
  const blob = new Blob([res], {
    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  })
  if (timeSuffix) {
    // 默认导出的文件名称添加时间
    const time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    name = name + ' ' + time
  }
  const fileName = `${name}.xlsx`
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveOrOpenBlob(blob, fileName)
  } else {
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  }
}

// Blob文件转换下载
// export const downBlobFile = (result, fileName, fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8;', submitEndDo?, timeSuffix = true) => {
//   const data = result
//   const blob = new Blob([data], { type: fileType })
//   if (timeSuffix) {
//     // 默认导出的文件名称添加时间
//     const time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
//     fileName = fileName + ' ' + time
//   }
//   if (window.navigator && window.navigator.msSaveOrOpenBlob) {
//     // for IE
//     // IE必须给文件名设置固定后缀，不然默认会是.txt
//     window.navigator.msSaveOrOpenBlob(blob, fileName + '.xls')
//   } else {
//     // for Non-IE (chrome, firefox etc.)
//     const objectUrl = URL.createObjectURL(blob)
//     const a = document.createElement('a')
//     a.setAttribute('style', 'display:none')
//     a.setAttribute('href', objectUrl)
//     // 指定导出excel的后缀名为xls，方便做打开
//     a.setAttribute('download', fileName + '.xls')
//     a.click()
//     URL.revokeObjectURL(objectUrl)
//   }
//   if (submitEndDo) {
//     submitEndDo()
//     submitEndDo = null
//   }
// }

interface TreeDataDts {
  id: string
  name: string
  children: TreeDataDts[]
  sapMatCodes: { name: string; code: string }[]
}
type TreeDatasDts = TreeDataDts[]

//树形遍历
export const treeMap = (data: TreeDatasDts) => {
  data = data || []
  return data.map(item => {
    if (!item.children) {
      item.children = []
    }
    return {
      value: item.id,
      label: item.name,
      children: treeMap(item.children),
    }
  })
}

// 获取oss文件key
export const getOssFileKey = url => {
  const findIndexString = '.aliyuncs.com/'
  const index = url.indexOf(findIndexString)
  const key = url.substring(index + findIndexString.length)
  return key
}

//树形遍历节点下所有子值
export const treeMapSap = (arr: any[], data: string[]) => {
  for (let i = 0; i < data.length; i++) {
    for (let a = 0; a < arr.length; a++) {
      if (arr[a].id === data[i]) {
        if (data.length !== i + 1) {
          arr = arr[a].children
        } else {
          return arr[a].sapMatCodes
        }
      }
    }
  }
}

/**
 * 处理formData格式参数中需要支持List[Map]类型的接口格式，目前只支持一层List[Map]数据，返回格式如：
  comment: 测试审批接口
  taskId: 27524
  userId: 421
  attachments[0].url: http://lzlj-jxsmh.oss-accelerate.aliyuncs.com/xxx.jpg
  attachments[0].name: {FD0AE82F-7F63-42F6-A68D-D740600A01FF}_20200310102847.jpg
  attachments[0].type: url
 * 使用qs.stringify()方法处理的formData数据如果是List[Map]格式的，会默认处理成attachments[0][url]，服务端无法接收
 * @param params 请求参数对象
 */
export function formatFormDataParams(params) {
  const formData = new FormData()
  for (const paramkey in params) {
    if (params.hasOwnProperty(paramkey)) {
      const param = params[paramkey]
      if (Array.isArray(param)) {
        let arr = param
        for (let i = 0; i < arr.length; i++) {
          if (typeof arr[i] === 'string') {
            // 如果是字符串数组，则不处理，传默认数组
            formData.append(`${paramkey}`, arr as any)
            break
          }
          for (let key in arr[i]) {
            formData.append(`${paramkey}[${i}].${key}`, arr[i][key])
          }
        }
      } else {
        formData.append(`${paramkey}`, params[paramkey])
      }
    }
  }
  return formData
}

export function isBlobBufferResponse(responseType) {
  return responseType == 'blob' || responseType == 'arraybuffer'
}

export function arraybufferToObject(arraybuffer) {
  let uint8: any = new Uint8Array(arraybuffer) // 提取uint8Array
  let fromCharCode = String.fromCharCode(...uint8)
  let resToString = decodeURIComponent(escape(fromCharCode))
  // 不是文件流数据，将转换好的数据重新覆盖
  return JSON.parse(resToString)
}

export function blobToObject(blob) {
  // 读取blob内容只能通过FileReader，且是异步读取到内容
  return new Promise((resolve, reject) => {
    var reader = new FileReader()
    reader.onload = function () {
      resolve(JSON.parse(reader.result as string))
    }
    reader.readAsText(blob, 'utf-8')
  })
}

// children默认会使table渲染成可展开树型table，这里需要替换children为其他字段名
export function replaceChildrenTableData(datas, oldKey = 'children', key = 'items') {
  if (!Array.isArray(datas) || datas.length < 1) {
    return datas
  }
  let res = []
  datas.map(data => {
    const { [oldKey]: children, ...reset } = data
    // 剔除oldKey数据
    let item = reset
    if (children) {
      // 使用新key替换oldKey的数据
      item[key] = replaceChildrenTableData(children)
    }
    res.push(item)
  })
  return res
}

// 获取盘点缓存数据
export const getCacheData = () => {
  const checkDataStr = window.sessionStorage.getItem('CheckData')
  return checkDataStr ? JSON.parse(checkDataStr) : {}
}

// 获取经销商缓存盘点数据
export const getCacheDataByDealerCode = (dealerCode: string) => {
  const cacheDataAll = getCacheData()
  return cacheDataAll[dealerCode]
}

// 删除经销商缓存数据
export const deleteCacheDataByDealerCode = (dealerCode: string) => {
  const cacheDataAll = getCacheData()
  delete cacheDataAll[dealerCode]

  window.sessionStorage.setItem('CheckData', JSON.stringify(cacheDataAll))
}

// 缓存盘点数据
export const setCacheData = (dealerCode: string, data: any) => {
  const cacheDataAll = getCacheData()
  const currData = getCacheDataByDealerCode(dealerCode)

  const checkData = {
    ...cacheDataAll,
    [dealerCode]: {
      ...currData,
      ...data,
    },
  }

  window.sessionStorage.setItem('CheckData', JSON.stringify(checkData))
}

//生成随机数
export function randomNumber(...rest) {
  // 生成 最小值 到 最大值 区间的随机数
  const random = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1) + min)
  }
  if (rest.length === 1) {
    let [length] = rest
    // 生成指定长度的随机数字，首位一定不是 0
    let nums = [...Array(length).keys()].map(i => (i > 0 ? random(0, 9) : random(1, 9)))
    return parseInt(nums.join(''))
  } else if (rest.length >= 2) {
    let [min, max] = rest
    return random(min, max)
  } else {
    return Number.NaN
  }
}

/**日期范围快捷选择 */
export const dataRange: any = {
  最近一周: [moment().startOf('day').subtract(1, 'weeks'), moment()],
  最近两周: [moment().startOf('day').subtract(2, 'weeks'), moment()],
  最近1个月: [moment().startOf('day').subtract(1, 'months'), moment()],
  最近3个月: [moment().startOf('day').subtract(3, 'months'), moment()],
  最近半年: [moment().startOf('day').subtract(6, 'months'), moment()],
  最近1年: [moment().startOf('day').subtract(1, 'years'), moment()],
}

const getFile = url => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url,
      responseType: 'arraybuffer',
    })
      .then(data => {
        resolve(data.data)
      })
      .catch(error => {
        reject(error.toString())
      })
  })
}

/**
 * @description: 批量打包下载
 * @param {*} params
 * @return {*}
 */
export const compressAndDownload = params => {
  const { data = [], downloadFileName = '压缩包', urlKey = 'fileUrl', nameKey = 'fileName' } = params
  const zip = new JSZip()
  const promises: any[] = []
  data.forEach((item: any) => {
    const promise = getFile(item[urlKey]).then((res: any) => {
      const flieNameStrArr = item[urlKey].split('.')
      const fileSuffix = flieNameStrArr[flieNameStrArr.length - 1]
      const fileName = `${item['dealerName']}-${item[nameKey]}-附件.${fileSuffix}`
      zip.file(fileName, res, { binary: true })
    })
    promises.push(promise)
  })

  Promise.all(promises).then(() => {
    zip
      .generateAsync({
        type: 'blob',
        compression: 'DEFLATE', // STORE：默认不压缩 DEFLATE：需要压缩
        compressionOptions: {
          level: 9, // 压缩等级1~9    1压缩速度最快，9最优压缩方式
        },
      })
      .then((res: any) => {
        FileSaver.saveAs(res, downloadFileName)
      })
  })
}

export const matchFileSuffixType = (fileName: string) => {
  // 后缀获取
  var suffix = ''
  // 获取类型结果
  var result: string | boolean = ''
  try {
    var flieArr = fileName.split('.')
    suffix = flieArr[flieArr.length - 1]?.toLowerCase()
  } catch (err) {
    suffix = ''
  }
  // fileName无后缀返回 false
  if (!suffix) {
    result = false
    return result
  }
  // 图片格式
  var imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif']
  // 进行图片匹配
  result = imglist.some(function (item) {
    return item === suffix
  })
  if (result) {
    result = 'image'
    return result
  }
  // 匹配txt
  var txtlist = ['txt']
  result = txtlist.some(function (item) {
    return item === suffix
  })
  if (result) {
    result = 'txt'
    return result
  }
  // 匹配 excel
  var excelist = ['xls', 'xlsx']
  result = excelist.some(function (item) {
    return item === suffix
  })
  if (result) {
    result = 'excel'
    return result
  }
  // 匹配 word
  var wordlist = ['doc', 'docx']
  result = wordlist.some(function (item) {
    return item === suffix
  })
  if (result) {
    result = 'word'
    return result
  }
  // 匹配 pdf
  var pdflist = ['pdf']
  result = pdflist.some(function (item) {
    return item === suffix
  })
  if (result) {
    result = 'pdf'
    return result
  }
  // 匹配 ppt
  var pptlist = ['ppt']
  result = pptlist.some(function (item) {
    return item === suffix
  })
  if (result) {
    result = 'ppt'
    return result
  }
  // 匹配 视频
  var videolist = ['mp4', 'm2v', 'mkv']
  result = videolist.some(function (item) {
    return item === suffix
  })
  if (result) {
    result = 'video'
    return result
  }
  // 匹配 音频
  var radiolist = ['mp3', 'wav', 'wmv']
  result = radiolist.some(function (item) {
    return item === suffix
  })
  if (result) {
    result = 'radio'
    return result
  }
  // 其他 文件类型
  result = 'other'
  return result
}

/**
 * @description: 单文件下载
 * @param {string} url
 * @return {*}
 */
export const handDownload = (url: string) => {
  const rex = /^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?/
  if (rex.test(url)) {
    window.open(url, '__blank')
  } else {
    message.error('附件URL无效')
  }
}

/**
 * @description: 设置setLocalStorage
 * @param {*} key
 * @param {*} value
 * @return {*}
 */
export function setLocalStorage(key, value) {
  window.localStorage.setItem(key, window.JSON.stringify(value))
}

/**
 * @description: 获取getLocalStorage
 * @param {*} key
 * @return {*}
 */
export function getLocalStorage(key) {
  return window.JSON.parse(window.localStorage.getItem(key))
}

/**
 * @description: 设置setSessionStorage
 * @param {*} key
 * @param {*} value
 * @return {*}
 */
export function setSessionStorage(key, value) {
  window.sessionStorage.setItem(key, window.JSON.stringify(value))
}

/**
 * @description: 获取getSessionStorage
 * @param {*} key
 * @return {*}
 */
export function getSessionStorage(key) {
  return window.JSON.parse(window.sessionStorage.getItem(key))
}

export function transformSearchValue(params:Record<string,any>):Record<string,any>{
    let searchValues = params
    let keys = Object.keys(searchValues)
    for (let key of keys) {
      if (key.includes('|')) {
        let value = searchValues[key]
        let keyArr = key.split('|')
        searchValues[keyArr[0]] = value?.[0]
        searchValues[keyArr[1]] = value?.[1]
        delete searchValues[key]
      }
    }
    return searchValues
}
// 检测公司是否重复
export function checkOptions(params:any[]){
  let result:any = params.map(item=>{
    return item.brandCode
  })
  result = new Set(result)
  return result
}


